//
//  LoginViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/14.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "LoginViewController.h"
#import <AFNetworking.h>
#import "WXApi.h"
#import "AllHeader.h"
#import "NSString+MD5.h"
//#import "UserInfoModel.h"

#import <UIImageView+WebCache.h>

//#define loginURL @"http://arts1.dlab.com.cn/app/login"
#define loginURL @"http://arts1.cn/app/login"
#define tokenURL @"http://www.arts1.cn/app/get_rongcloud_token"

#define kURL @"http://arts1.cn/app/myinfo"





@interface LoginViewController ()<UITextFieldDelegate>

@property (nonatomic,strong) NSDictionary *tokenDic;
@property (nonatomic,strong) NSDictionary *userInfoDict;


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self modifysubview];
    [self isHidenThirdBtn];
    
}

- (void)modifysubview{
    //  设置头像为圆形
    _iconImageView.layer.cornerRadius = _iconImageView.bounds.size.height / 2;
    _iconImageView.layer.masksToBounds = YES;
    _iconImageView.userInteractionEnabled = YES;
    
    // 设置textField的代理
    _userLabel.delegate = self;
    _password.delegate = self;
    
    NSDictionary *phoneDic = [[NSUserDefaults standardUserDefaults] objectForKey:@"PhoneAndPassword"];
    NSDictionary *faceNike = [[NSUserDefaults standardUserDefaults] objectForKey:@"userFace"];
    
    _userLabel.text = phoneDic[@"phone"];
    _password.text = phoneDic[@"password"];
    _nikeName.text = faceNike[@"nickName"];
    
    [_iconImageView sd_setImageWithURL:[NSURL URLWithString: faceNike[@"userFace"]] placeholderImage:nil options:(SDWebImageRetryFailed | SDWebImageLowPriority)];
}



// 点击登陆
- (IBAction)clickLoginBTN:(id)sender
{
    // 记录登录状态
    [[NSUserDefaults standardUserDefaults] setObject:@"login" forKey:@"LoginState"];
    //调用登录请求方法
   [self requestLogin];
}

//登录请求
- (void)requestLogin
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
   
    //加密
    NSString *pwdResult = [NSString MD5WithString:_password.text];
    
    NSDictionary * usreDic = @{@"phone":_userLabel.text,@"password":_password.text};
    
    //请求参数
    NSDictionary *pardic = @{@"phone":_userLabel.text,@"password":pwdResult};

    [manage POST:loginURL parameters:pardic
      success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        // 请求成功的时候调用这个block
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
        //记录请求返回结果
        NSString *statusStr = nil;
        //返回的状态
        int index = [dic[@"status"] intValue];
        switch (index)
        {
            case 1:
            {
                // 登陆成功之后，使用NSUserDefaults存储返回的key和uid以及status（状态为1时，表示登陆成功）对应的key值为dataForKeyAndUid
                [[NSUserDefaults standardUserDefaults] setValue:dic forKey:@"dataForKeyAndUid"];

                [[NSUserDefaults standardUserDefaults]setValue:usreDic forKeyPath:@"PhoneAndPassword"];
                
                statusStr =nil;
                //请求成功后，请入首页面
                if(_loginblock)
                {
                    _loginblock(1);
                }
                
                [self requestToken];
                
            }
                break;
            case 0:
                statusStr = @"输入不完整";
                break;
            case -1:
                statusStr = @"用户名或密码错误";
                break;
            case -2:
                statusStr = @"手机号码不符合规范";
                break;
                
            default:
                break;
        }
        
        if (statusStr)
        {
            //信息提示框
           [MBProgressHUD show:statusStr icon:nil view:self.view];
        }
        
        NSLog(@"登陆成功后返回数据 ： %@", dic);
        
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          // 请求失败的时候调用调用这个block
          NSLog(@"请求失败");
      }];

}


/**
 *  请求数据
 */
- (void)requestToken
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSString *uid = dic[@"data"][@"uid"];
    NSString *key = dic[@"data"][@"key"];
    
    NSDictionary *pardic = [NSDictionary dictionary];
    
    if (uid && key)
    {
        pardic = @{@"uid":uid,
                   @"key":key};
    }
    
    
    [manage POST:tokenURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             
             int status = [dic[@"status"] intValue];
             NSString *str = nil;
             switch (status) {
                 case 1:{
                     str = @"获取成功";
                     _tokenDic = dic;
                     [self requestUserInfo];
                 }
                     break;
                 case 0:
                     str = @"获取失败";
                     break;
                 case -1:
                     str = @"用户名或密码为空";
                     break;
                 case -2:
                     str = @"用户名或密码错误";
                     break;
                 default:
                     break;
             }
             
             // 请求成功的时候调用这个block
             NSLog(@"token ==== %@",_tokenDic);
             [self loginRongCloud];
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}



//  请求用户信息
- (void)requestUserInfo
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    NSString *key = dic[@"data"][@"key"];
    NSDictionary *pardic = nil;
    if (uid && key)
    {
        pardic = @{@"uid":uid,
                   @"key":key};
    }
    
    [manage POST:kURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         // 请求成功的时候调用这个block
         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
         
         int status = [dic[@"status"] intValue];
         if (status == 1)
         {
             NSDictionary *dict = dic[@"data"];
             
             _userInfoDict = dict;

         }
     }
         failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败------%@",error);
     }];
}

/**
 *登录融云
 *
 */
-(void)loginRongCloud
{
    //登录融云服务器,开始阶段可以先从融云API调试网站获取，之后token需要通过服务器到融云服务器取。
    NSString *token = _tokenDic[@"rongcloud"][@"token"];
    NSLog(@"%@",_tokenDic);
    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        
        //设置用户信息提供者,页面展现的用户头像及昵称都会从此代理取
        [[RCIM sharedRCIM] setUserInfoDataSource:self];
        [self getUserInfoWithUserId:userId completion:^(RCUserInfo *userInfo) {
            nil;
        }];
        
        NSLog(@"Login successfully with userId: %@.", userId);
        dispatch_async(dispatch_get_main_queue(), ^{
//            ChatListViewController *chatListViewController = [[ChatListViewController alloc]init];
//            [self.navigationController pushViewController:chatListViewController animated:YES];
        });
        
    } error:^(RCConnectErrorCode status) {
        NSLog(@"login error status: %ld.", (long)status);
    } tokenIncorrect:^{
        NSLog(@"token 无效 ，请确保生成token 使用的appkey 和初始化时的appkey 一致");
    }];
    
}

/**
 *此方法中要提供给融云用户的信息，建议缓存到本地，然后改方法每次从您的缓存返回
 */
- (void)getUserInfoWithUserId:(NSString *)userId completion:(void(^)(RCUserInfo* userInfo))completion
{
    //此处为了演示写了一个用户信息
    if ([_userInfoDict[@"userId"] isEqual:userId]) {
        RCUserInfo *user = [[RCUserInfo alloc]init];
        user.userId = _userInfoDict[@"userId"];
        user.name = _userInfoDict[@"nickName"];
        user.portraitUri = _userInfoDict[@"userFace"];
        
        NSLog(@"userID == %@",user.userId);
        NSLog(@"user.name == %@",user.name);
        NSLog(@"portraitUri == %@",user.portraitUri);
        
        return completion(user);
    }
}



// 判断是否有微信客户端，如果没有隐藏微信第三方登录按钮
- (void)isHidenThirdBtn
{
    // 判断用户手机是否安装微信客户端
    BOOL WXinstalled =  [WXApi isWXAppInstalled];
    // 如果未安装就隐藏微信登陆按钮
    if (!WXinstalled) {
        self.weixinlogin.hidden = YES;
        self.weixinlogin.userInteractionEnabled = NO;
    }
}

// 微信登陆
- (IBAction)incognitologin:(id)sender
{
    if(_loginblock)
    {
        _loginblock(4);
    }
}




// 触摸空白区域取消编辑
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

//
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField == _userLabel) {
        [_password becomeFirstResponder];
    } else{
        [self.view endEditing:YES];
    }
    return YES;
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
